from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from help import *
from lib.redis_db import *
import time



class File(Resource):
    def __init__(self):
        self.rdex = RedisExe()
    def get(self):
        imglist = self.rdex.getValue("imglist")
        if imglist:
            imglist = eval(imglist)
            imglist = ["https://zhao.ink/"+i for i in imglist][::-1]
        return {"code": 200, "data": {"imglist":imglist,"time":self.rdex.getValue()}, "msg": "图片上传最新时间"}
    def patch(self):
        #文件上传到阿里OSS
        rq = RequestParser()
        rq.add_argument("pic",type = check_img,required = True,location="files")
        req = rq.parse_args()
        #把文件上传时间存储到redis
        curTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.rdex.setValue("time",curTime)
        #历史头像信息存储
        imgname = str(time.time()).replace(".","")+".png"
        imgdata = req.pic.read()
        #已上传的头像
        up_img(imgdata, name="1.png")
        #添加到oss文件夹
        up_img(imgdata, name=imgname)
        #获取已有的头像列表
        imglist = self.rdex.getValue("imglist")
        #不存在则构建新头像列表
        if not imglist:
            imglist = "[]"
            self.rdex.setValue("imglist","[]")
        imglist = eval(imglist)
        imglist.append(imgname)
        self.rdex.setValue("imglist", str(imglist))
        #构建头像新列表信息
        imglist = ["https://zhao.ink/" + i for i in imglist][::-1]
        return {"code":200,"data":{"imglist":imglist,"time":self.rdex.getValue()},"msg":"图片上传上传"}